/**
 * Created by Eoly on 2017/3/27.
 * Call http://palerock.cn
 */

var app = angular.module('app', ['ngRoute']);
app.tuijieList = [];
// 设置页面地址文件夹
app.pagePath = 'page/';

// 设置项目后端根目录地址
// app.netPath = 'http://localhost:8080';
app.netPath = 'http://www.xiaowenxiong.cn/sf_car';

// 设置模板页面后缀名
app.modelName = 'html';

// app按返回键按钮
app.backEvent = function () {
    var model = $('.modal-overlay-visible');
    // 若有遮挡层则无动作
    if (model.length > 0) {
        $.closeModal($('.popup'));
        $.closeModal(".actions-modal.modal-in");
        $('.popup-overlay').removeClass('modal-overlay-visible');
        return;
    }
    // 若有panel则关闭
    if ($('.with-panel-left-reveal').length > 0) {
        $.closePanel();

        return;
    }


    var a = $('a.icon-left');
    if (a.length > 0) {
        a.click();
    } else {
        history.back();
    }
    return 'back successfully';
};
//图片旋转加载
app.buildImageUrl = function (imageObject, pname, cb) {
    var img = new Image();
    var src = imageObject[pname];
    img.onload = function () {
        imageObject[pname] = src;
        if (cb || cb instanceof Function) {
            cb.call(window);
        }
    };
    img.src = src;
    imageObject[pname] = 'lib/res/load.gif';
};

//图片分割（","）
app.getDynamicImg = function (dynamicImgString) {
    var dynamicImg = dynamicImgString.split(',');
    return dynamicImg;
};


// 过滤器
app.filter('statusFilter', function () {
    return function (e) {

        switch (e) {
            case 0:
                return '待完成';
            case 1:
                return '已完成';
            case 2:
                return '失效';
            default:
                return '未知状态'
        }
    }
});
app.filter('deadlineChange', function () {
        return function (e) {
            if (e) {
                if (e <= 0) {
                    return;
                }
                else {
                    return '截止时间还有' + e + '天';
                }
            }

        }
    }
);
app.filter('distanceChangeFilter', function () {
    return function (e) {
        return (e / 1000.00).toFixed(2) + 'km';
    }
});

app.filter('parsePriceFilter', function () {
    return function (e) {

        if (e.minPrice == null && e.maxPrice == null) {
            return '无限制'
        }

        if (e.minPrice == null) {
            return '<¥' + e.maxPrice;
        } else if (e.maxPrice == null) {
            return '>¥' + e.minPrice;
        }

        return '¥' + e.minPrice + '--' + e.maxPrice;
    }
});


// 设置默认控制器（该控制器中使用$scope存放的数据在所有页面均可以共享）
app.controller('default', function ($http, $scope) {

    $scope.your = 'some content';
    // 初始化sui框架
    $scope.suiMobileInit = function (jsPath) {
        app.suiInit(jsPath);


    };

    $scope.initCss = function (cssPath) {
        app.initCss(cssPath);
    };

    $scope.$on('$viewContentLoaded', function (event) {
        var jsPlus = document.getElementById("page-js");
        if (jsPlus.childNodes[0]) {
            jsPlus.removeChild(jsPlus.childNodes[0]);
        }
        $(document).off('infinite', '.infinite-scroll');
    });
    //图片浏览器
    $scope.showImg = function (imgObjects, index) {
        var imgs = [];
        for (var i = 0; i < imgObjects.length; i++) {
            if (typeof imgObjects[i] == 'string') {
                imgs.push(imgObjects[i]);
                continue;
            }
            imgs.push(imgObjects[i].imgSrc);
        }
        /*=== Popup ===*/
        var myPhotoBrowserStandalone = $.photoBrowser({
            photos: imgs,
            type: 'popup',
            initialSlide: index
        });
        //点击时打开图片浏览器
        myPhotoBrowserStandalone.open();
    };

    //查询登录用户收藏动态列表
    $scope.tourIdList = [];
    $scope.showCollectionList = function (token) {
        if (!token) {
        } else {
            $scope.tourIdList = [];
            //收藏动态列表id
            $http({
                method: 'get',
                url: app.netPath + '/collection/show',
                headers: {'Authorization': token}
            }).then(function (res) {
                if (!res.data.error) {
                    for (var i = 0; i < res.data.data.length; i++) {
                        $scope.tourIdList.push(res.data.data[i].collDynaid);
                    }
                }
                else {

                }
            }, function () {
                $.toast('网络走丢了！')
            });
        }
    };

    // 更多...
});

app.isPlusReady = false;
// 扩展API加载完毕后调用onPlusReady回调函数
document.addEventListener("plusready", onPlusReady, false);
// 扩展API加载完毕，现在可以正常调用扩展API  
function onPlusReady() {
    app.isPlusReady = true;
    var isPreToExitOne = false;
    var isPreToExitTwo = false;
    plus.key.addEventListener('backbutton', function () {
        if (isPreToExitTwo) {
            plus.runtime.quit();
        }
        if (!isPreToExitOne) {
            app.backEvent();
            isPreToExitOne = true;
            window.setTimeout(function () {
                isPreToExitOne = false;
            }, 500)
        } else {
            isPreToExitTwo = true;
            window.setTimeout(function () {
                isPreToExitTwo = false;
            }, 800);
            $.toast('再次按返回键退出', 800, 'toastToBot');
        }
    }, false);
    plus.geolocation.getCurrentPosition(function (p) {
        app.addressInfo = p;
    }, function (e) {
        console.log("Gelocation Error: code - " + e.code + "; message - " + e.message);
        switch (e.code) {
            case e.PERMISSION_DENIED:
                $.alert("User denied the request for Geolocation.");
                break;
            case e.POSITION_UNAVAILABLE:
                $.alert("Location information is unavailable.");
                break;
            case e.TIMEOUT:
                $.alert("The request to get user location timed out.");
                break;
            case e.UNKNOWN_ERROR:
                $.alert("An unknown error occurred.");
                break;
        }
    });
    setInterval(function () {
        plus.geolocation.getCurrentPosition(function (p) {
            if (p != null && p.coords != null && p.coords.latitude != null && p.coords.longitude) {
                app.addressInfo = p;
            }
        }, function (e) {
            console.log("Gelocation Error: code - " + e.code + "; message - " + e.message);
            switch (e.code) {
                case e.PERMISSION_DENIED:
                    $.alert("User denied the request for Geolocation.");
                    break;
                case e.POSITION_UNAVAILABLE:
                    $.alert("Location information is unavailable.");
                    break;
                case e.TIMEOUT:
                    $.alert("The request to get user location timed out.");
                    break;
                case e.UNKNOWN_ERROR:
                    $.alert("An unknown error occurred.");
                    break;
            }
        });
    }, 20000);
}

//app.run(['$rootScope',  function($rootScope){
////监听路由事件
//
//    $rootScope.$on('$stateChangeStart',
//
//        function(event, toState, toParams, fromState, fromParams){
//
//            var jsPlus = document.getElementById("page-js");
//            jsPlus.removeChild(jsPlus.childNodes[0]);
//            console.log('asdasdasasdasdasdasd')
//            event.preventDefault();
//
//        })
//
//}]);

// 路由的一个页面
app.Page = function (templateUrl) {
    this.path = '';
    this.templateUrl = app.pagePath + templateUrl;
    this.controller = '';

    var _this = this;
    var init = function () {
        var parts = templateUrl.split("/");
        var name = parts[parts.length - 1].split('.')[0];
        _this.path = '/' + name;
        _this.controller = name;
    };
    init();

    // 设置单个路由的页面路径
    this.setPath = function (path) {

        if (!path) {
            return this;
        }
        this.path = path;

        return this
    };

    // 设置单个路由的控制器名称
    this.setController = function (controller) {

        if (!controller) {
            return this;
        }
        this.controller = controller;

        return this
    }
};


app.getGreatCircleDistance = function (lat1, lng1) {
    var lat2, lng2;
    if (!app.isPlusReady || !app.addressInfo) {
        // 地址未获取成功
        // return
        lat2 = 30.88178;
        lng2 = 104.877946
    } else {
        //地址获取成功
        lat2 = app.addressInfo.coords.latitude;
        lng2 = app.addressInfo.coords.longitude;
    }

    if (lat1 == lat2 && lng1 == lng2) {
        return 1;
    }


    var EARTH_RADIUS = 6378137.0;    //单位M
    var PI = Math.PI;
    var getRad = function (d) {
        return d * PI / 180.0;
    };

    var f = getRad((lat1 + lat2) / 2);
    var g = getRad((lat1 - lat2) / 2);
    var l = getRad((lng1 - lng2) / 2);

    var sg = Math.sin(g);
    var sl = Math.sin(l);
    var sf = Math.sin(f);

    var s, c, w, r, d, h1, h2;
    var a = EARTH_RADIUS;
    var fl = 1 / 298.257;

    sg = sg * sg;
    sl = sl * sl;
    sf = sf * sf;

    s = sg * (1 - sl) + (1 - sf) * sl;
    c = (1 - sg) * (1 - sl) + sf * sl;

    w = Math.atan(Math.sqrt(s / c));
    r = Math.sqrt(s * c) / w;
    d = 2 * w * a;
    h1 = (3 * r - 1) / 2 / c;
    h2 = (3 * r + 1) / 2 / s;


    var distance = d * (1 + fl * (h1 * sf * (1 - sg) - h2 * (1 - sf) * sg));
    if (distance == 0) {
        distance = 1;
    }
    return parseInt(distance);
};

// 路由里的一组页面
app.PageGroup = function () {

    // 页面组
    this.pages = [];

    // 默认页面路径
    this.defaultPath = '/test';

    // 设置默认页面路径
    this.setDefault = function (path) {
        for (var i = 0; i < this.pages.length; i++) {
            if (path == this.pages[i].path) {
                this.defaultPath = path;
                break;
            }
        }
    };

    // 向路由中添加页面
    this.addPage = function (templateUrl) {
        var page = new app.Page(templateUrl);
        this.pages.push(page);
        return page;
    };

    // 设置单个路由的页面路径
    this.setPath = function (index, path) {
        if (!index || !path) {
            return;
        }
        this.pages[index].path = path;
        console.log('modify path:' + path + ' successfully.')
    };

    // 设置单个路由的控制器名称
    this.setController = function (index, controller) {
        if (!index || !controller) {
            return;
        }
        this.pages[index].controller = controller;
        console.log('modify controller:' + controller + ' successfully.')
    };

    // 生成整体路由
    this.buildRouter = function (application) {
        var _this = this;
        application.config(
            function ($routeProvider) {
                for (var i = 0; i < _this.pages.length; i++) {
                    $routeProvider.when(_this.pages[i].path, {
                        templateUrl: _this.pages[i].templateUrl,
                        controller: _this.pages[i].controller
                    });
                    console.log("router page:" + _this.pages[i].path + " load successfully.");
                }
                $routeProvider.otherwise({
                    redirectTo: _this.defaultPath
                });
                console.log("default page:" + _this.defaultPath + " set successfully.");
            }
        );
        this.initController(application);
    };

    // 初始化控制器
    this.initController = function (application) {
        for (var i = 0; i < this.pages.length; i++) {
            application.controller(this.pages[i].controller, function () {
            })
        }
    }
};

// 实例化路由页面组，交移page-admin页面处理
app.pageGroup = new app.PageGroup();


// Sui框架初始化的党法，需要在每个模版页面的末尾添加（勿改动）
app.initCss = function (cssPlusPath) {
    // 修改css样式
    var cssPlus = document.getElementById("page-css");

    cssPlus.href = '';

    if (cssPlusPath) {
        cssPlus.href = app.pagePath + cssPlusPath;
    }

};
app.suiInit = function (jsPlusPath) {



    // 默认的init 方法
    var $page = $(".page-current");
    if (!$page[0]) $page = $(".page").addClass('page-current');
    var id = $page[0].id;
    if (!$page[0]) $page = $(document.body);
    var $content = $page.hasClass('content') ?
        $page :
        $page.find('.content');
    $content.scroller();  //注意滚动条一定要最先初始化

    $.initPullToRefresh($content);
    $.initInfiniteScroll($content);
    $.initCalendar($content);

    //extend
    // if ($.initSwiper) $.initSwiper($content);

    $page.trigger('pageInit', [id, $page]);

    // 增加js代码
    var jsPlus = document.getElementById("page-js");
    if (jsPlus.childNodes[0]) {
        jsPlus.removeChild(jsPlus.childNodes[0]);
    }
    if (jsPlusPath) {
        var script = document.createElement("script");
        script.src = app.pagePath + jsPlusPath;
        jsPlus.appendChild(script);
    }

    //初始化侧边栏
    $.closePanel();
    console.log($.closePanel())
    if (!$.closePanel()) {
        $('.panel-left').hasClass('active');
        $('body').attr('class', null);
        $('.panel-left').removeClass('active');
        $('.panel-left').css('display', "");
    }

};

app.cutImgByBase64 = function (w, h, base64, cb) {

};